Yes, this would work. But it would be tedious.
The reversed String
could be built up character by character in an array.
Since arrays can be altered,
only one new object would
be constructed.
This is essentially the idea of the StringBuffer
class.
A StringBuffer
object holds characters that
can be changed by appending and by inserting characters.
Also, a StringBuffer
object includes
many useful character manipulation methods.
If you insert characters into a StringBuffer
,
it automatically grows to the length you need.
This relieves much of the tedium that directly using an array would involve.
Constructors for StringBuffer
are:
StringBuffer constructors | |
---|---|
public StringBuffer() | create an empty StringBuffer |
public StringBuffer(int capacity) | create a StringBuffer with initial room for capacity number of characters |
public StringBuffer(String str) | create a StringBuffer containing the characters from str |
Why would you ever want a StringBuffer
with length zero?